﻿Public Class FormInvoiceAdd

    Dim subtotal As Double = 0
    Dim total As Double = 0
    Private Sub FormInvoiceAdd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        UI.FormatDataGrid(dgv)

        Me.dgv.ReadOnly = False
        For Each column As DataGridViewColumn In Me.dgv.Columns
            column.ReadOnly = True
        Next
        Me.dgv.Columns("Qty").ReadOnly = False
        Me.dgv.Columns("Price").ReadOnly = False

        Me.txtInNo.Text = NoGenerator.GenerateInvoiceNo

        txtInNo.Enabled = False
        dtpDate.Enabled = False
        txtSubTotal.Enabled = False
        txtTotal.Enabled = False

        loadstore()
        loadCustomer()

    End Sub
    Private Sub loadstore()
        Me.cboStore.DisplayMember = "StoreName"
        Me.cboStore.ValueMember = "StoreId"
        Me.cboStore.DataSource = Cmd.ExecuteDataTable("SELECT * FROM Store WHERE Active=1")
    End Sub
    Private Sub loadCustomer()
        Me.cboCus.DisplayMember = "Customer"
        Me.cboCus.ValueMember = "CustomerId"
        Me.cboCus.DataSource = Cmd.ExecuteDataTable("SELECT CustomerId,Customer = CustomerName+' ('+Phone+')' FROM Customer WHERE Active=1")
    End Sub

    Private Sub BrowseProduct()
        Dim frm As New FormProductBrowser()
        frm.txtSearch.Text = Me.txtProCode.Text
        If frm.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Dim row = frm.dgv.SelectedRows(0)
            Me.txtProId.Text = row.Cells("ProductId").Value
            Me.txtProCode.Text = row.Cells("ProductCode").Value
            Me.txtProName.Text = row.Cells("ProductName").Value
            Me.txtPrice.Text = row.Cells("Price").Value
            Me.txtQty.Text = "1"
            Me.txtAmount.Text = Me.txtPrice.Text
        End If
    End Sub

    Private Sub btnaddpro_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnaddpro.Click
        BrowseProduct()
    End Sub

    Private Sub txtQty_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtQty.TextChanged, txtPrice.TextChanged
        Dim amount As Double = Val(Me.txtPrice.Text) * Val(Me.txtQty.Text)
        Me.txtAmount.Text = amount.ToString("#,##0.00")
    End Sub

    Private Sub btnAddLine_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddLine.Click
        If txtProName.Text = "" Then
            MessageBox.Show("Please choose any product!")
            Exit Sub
        End If
        Dim searchRow = FindProductInList(Me.txtProId.Text)

        If searchRow Is Nothing Then
            Dim i = Me.dgv.Rows.Add()
            Dim row = Me.dgv.Rows(i)
            row.Cells("ProductId").Value = Me.txtProId.Text
            row.Cells("ProductCode").Value = Me.txtProCode.Text
            row.Cells("ProductName").Value = Me.txtProName.Text
            row.Cells("Price").Value = Val(Me.txtPrice.Text)
            row.Cells("Qty").Value = Val(Me.txtQty.Text)
            row.Cells("Amount").Value = Val(Me.txtAmount.Text)
        Else
            searchRow.Cells("Qty").Value = searchRow.Cells("Qty").Value + Val(Me.txtQty.Text)
            searchRow.Cells("Price").Value = (Me.txtPrice.Text)
            searchRow.Cells("Amount").Value = Val(searchRow.Cells("Qty").Value) * Me.txtPrice.Text
        End If
        'getotal()
        ClearLine()
        Me.txtSubTotal.Text = CalculateSubTotal().ToString("N2")

    End Sub
    Private Sub getotal()
        
        subtotal = subtotal + Val(txtAmount.Text)
        total = subtotal - ((subtotal * Val(txtDiscount.Text)) \ 100)
        txtSubTotal.Text = subtotal.ToString("#,##0.00")
        txtTotal.Text = total.ToString("#,##0.00")
    End Sub

    Private Function FindProductInList(ByVal id As Int16) As DataGridViewRow
        For Each row As DataGridViewRow In Me.dgv.Rows
            If row.Cells("ProductId").Value = id Then
                Return row
            End If
        Next
        Return Nothing
    End Function

    Private Sub ClearLine()
        Me.txtProId.Text = ""
        Me.txtProName.Text = ""
        Me.txtQty.Text = ""
        Me.txtPrice.Text = ""
        Me.txtAmount.Text = ""
        Me.txtProCode.Text = ""
        Me.txtProCode.Focus()
    End Sub

    Private Sub txtDiscount_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtDiscount.TextChanged
        UpdateTotal()
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Try
            Cmd.Begin()
            Cmd.Parameters("@invNo") = Me.txtInNo.Text
            Cmd.Parameters("@invDate") = Me.dtpDate.Value
            Cmd.Parameters("@cusId") = Me.cboCus.SelectedValue
            Cmd.Parameters("@StoreId") = Me.cboStore.SelectedValue
            Cmd.Parameters("@SubTotal") = Parse.ToDecimal(Me.txtSubTotal.Text)
            Cmd.Parameters("@Discount") = Parse.ToDecimal(Me.txtDiscount.Text)
            Cmd.Parameters("@Total") = Parse.ToDecimal(Me.txtTotal.Text)
            Cmd.ExecuteNonQuery("INSERT INTO Invoice VALUES(@invNo,@invDate,@cusId,@StoreId,@Subtotal,@Discount,@Total,1);")

            Dim id = Cmd.ExecuteScalar("SELECT Max(InvoiceId) FROM Invoice;")

            For Each row As DataGridViewRow In Me.dgv.Rows
                Cmd.Parameters("@invId") = id
                Cmd.Parameters("@ProductId") = row.Cells("ProductId").Value
                Cmd.Parameters("@Qty") = row.Cells("Qty").Value
                Cmd.Parameters("@Price") = row.Cells("Price").Value
                Cmd.Parameters("@Amount") = row.Cells("Amount").Value
                Cmd.ExecuteNonQuery("INSERT INTO InvoiceDetail VALUES(@invId,@ProductId,@Qty,@Price,@Amount,1);")
            Next

            For Each row As DataGridViewRow In Me.dgv.Rows
                Cmd.Parameters("@StoreId") = Me.cboStore.SelectedValue
                Cmd.Parameters("@ProductId") = row.Cells("ProductId").Value
                Cmd.Parameters("@Qty") = row.Cells("Qty").Value
                Cmd.ExecuteNonQuery("UPDATE Stock SET Qty = Qty - @qty  WHERE ProductId=@ProductId AND StoreId = @StoreId")
            Next

            Cmd.Commit()

        Catch ex As Exception
            Cmd.Rollback()
            MsgBox(ex.Message)
        End Try

        Me.Close()
    End Sub

    Private Sub txtProCode_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtProCode.KeyDown
        If e.KeyCode <> Keys.Enter Then
            Exit Sub
        End If


        Cmd.Parameters("@Code") = Me.txtProCode.Text
        Dim dt = Cmd.ExecuteDataTable("SELECT * FROM Product WHERE ProductCode=@Code")

        If (dt.Rows.Count = 0) Then
            BrowseProduct()
            ClearLine()
            Exit Sub
        End If

        Dim row = dt.Rows(0)
        Me.txtProId.Text = row("ProductId")
        Me.txtProName.Text = row("ProductName")
        Me.txtPrice.Text = row("Price")
        Me.txtQty.Text = 1
        Me.txtAmount.Text = txtPrice.Text
    End Sub

    Private Sub dgv_CellValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv.CellValueChanged
        If e.RowIndex = -1 Then
            Exit Sub
        End If

        Dim row = Me.dgv.Rows(e.RowIndex)
        Dim qty As Decimal = row.Cells("Qty").Value
        Dim price As Decimal = row.Cells("Price").Value
        Dim amount = qty * price
        row.Cells("Amount").Value = amount
        Me.txtSubTotal.Text = CalculateSubTotal().ToString("N2")
    End Sub

    Private Function CalculateSubTotal() As Decimal
        Return Me.dgv.Rows.Cast(Of DataGridViewRow).Sum(Function(x) x.Cells("AMOUNT").Value)
    End Function

    Private Sub UpdateTotal()
        Dim subtotal = Parse.ToDecimal(Me.txtSubTotal.Text)
        Dim discount = Parse.ToDecimal(Me.txtDiscount.Text)
        Dim total = subtotal - (subtotal * discount / 100.0)
        Me.txtTotal.Text = total.ToString("N2")
    End Sub

    Private Sub txtSubTotal_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSubTotal.TextChanged
        UpdateTotal()
    End Sub
End Class